//
//  GoodsSelectVC.m
//  BonweBuy
//
//  Created by liuxin on 2020/2/24.
//  Copyright © 2020 liuxin. All rights reserved.
//

#import "GoodsSelectVC.h"
#import "SelectHeadView.h"
#import "BuyInfoModel.h"
#import "GoodsDetailSpecTitleView.h"
#import "GoodsSpecificationCell.h"
#import "GoodsDetailBuyCountView.h"
#import "LXWaterFlowLayout.h"

@interface GoodsSelectVC ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) SelectHeadView *headView;
@property (nonatomic, strong) BuyInfoModel *buyInfoModel;
@property (nonatomic, strong) UICollectionView *myCollectionView;
@property (nonatomic, strong) NSMutableArray *skuArray;//满足条件的
@property (nonatomic, strong) GoodsDetailBuyCountView *countView;
@end

@implementation GoodsSelectVC

#pragma mark - add键盘事件的监听
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

#pragma mark - remove键盘事件的监听
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}

-(void)dealloc{
    [self.buyInfoModel removeObserver:self forKeyPath:@"colorModel"];
    [self.buyInfoModel removeObserver:self forKeyPath:@"sizeModel"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.buyInfoModel = [BuyInfoModel new];
    self.buyInfoModel.count = 1;
    
    [self.buyInfoModel addObserver:self forKeyPath:@"colorModel" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.buyInfoModel addObserver:self forKeyPath:@"sizeModel" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    //添加头部视图
    [self.view addSubview:self.headView];
    [_headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.mas_equalTo(0);
        make.height.mas_equalTo(kAppWidth_Mini(740));
    }];
    
    self.headView.goodsModel = self.detailModel;
    self.headView.buyInfoModel = self.buyInfoModel;
    
    LXWaterFlowLayout *layout = [LXWaterFlowLayout new];
    layout.sectionInset = UIEdgeInsetsMake(kAppWidth_Mini(50), kAppWidth_Mini(50), kAppWidth_Mini(50), kAppWidth_Mini(50));
    layout.minimumLineSpacing = kAppWidth_Mini(50);
    layout.minimumInteritemSpacing = kAppWidth_Mini(50);
    UICollectionView *myCollectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    myCollectionView.delegate = self;
    myCollectionView.dataSource = self;
    myCollectionView.backgroundColor = [UIColor whiteColor];
    [myCollectionView registerClass:[GoodsDetailSpecTitleView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GoodsDetailSpecTitleView"];
    [myCollectionView registerClass:[GoodsDetailBuyCountView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"GoodsDetailBuyCountView"];
    [myCollectionView registerClass:[GoodsSpecificationCell class] forCellWithReuseIdentifier:@"GoodsSpecificationCell"];
    [self.view addSubview:myCollectionView];
    [myCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.mas_equalTo(0);
        make.top.equalTo(self.headView.mas_bottom);
    }];
    self.myCollectionView = myCollectionView;
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if ([keyPath isEqualToString:@"colorModel"]) {
        BuyInfoModel *new = change[@"new"];
        BuyInfoModel *old = change[@"old"];
        if (new != old) {
            self.headView.buyInfoModel = self.buyInfoModel;
            //查询尺码等信息
            [self getSkuCodes];
        }
    }else if([keyPath isEqualToString:@"sizeModel"]){
        BuyInfoModel *new = change[@"new"];
        BuyInfoModel *old = change[@"old"];
        if (new != old) {
            self.headView.buyInfoModel = self.buyInfoModel;
            //是否是置空操作
            if (self.buyInfoModel.sizeModel) {
                // 查询库存
                [self getSkuModel];
            }
        }
    }
}

#pragma mark - 改变颜色获取尺码
-(void)getSkuCodes{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"saleAttr1ValueCode = %@",self.buyInfoModel.colorModel.saleAttr1ValueCode];
    NSArray *resultarray = [self.detailModel.skuInfo filteredArrayUsingPredicate:predicate];
    NSArray *codeArray = [resultarray valueForKeyPath:@"saleAttr2ValueCode"];
    self.skuArray = [NSMutableArray arrayWithArray:codeArray];
    //判断是否选过尺码
    if(self.buyInfoModel.sizeModel){
        //判断上次选择的尺码,在新颜色上有没有
        if (![codeArray containsObject:self.buyInfoModel.sizeModel.saleAttr2ValueCode]) {
            //没有 清除上次选择
            self.buyInfoModel.sizeModel = nil;
            self.buyInfoModel.skuModel = nil;
        }else{
            //有 查询库存
            [self getSkuModel];
        }
    }
    [self.myCollectionView reloadData];
}

#pragma mark - 改变尺码更改购买数量
-(void)getSkuModel{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"saleAttr1ValueCode = %@ && saleAttr2ValueCode = %@",self.buyInfoModel.colorModel.saleAttr1ValueCode,self.buyInfoModel.sizeModel.saleAttr2ValueCode];
    NSArray *resultarray = [self.detailModel.skuInfo filteredArrayUsingPredicate:predicate];
    if (resultarray.count > 0) {
        self.buyInfoModel.skuModel = resultarray[0];
        [self.myCollectionView reloadData];
    }
}

#pragma mark - UICollectionDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.detailModel.saleAttrList.saleAttr2List.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SaleAttr2ListModel *model = self.detailModel.saleAttrList.saleAttr2List[indexPath.row];
    GoodsSpecificationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GoodsSpecificationCell" forIndexPath:indexPath];
    if (self.buyInfoModel.colorModel) {
        model.isStock = [self.skuArray containsObject:model.saleAttr2ValueCode];
    }else{
        model.isStock = YES;
    }
    cell.skuModel = model;
    return cell;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kAppWidth_Mini(150), kAppWidth_Mini(90));
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, kAppWidth_Mini(80));
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeMake(SCREEN_WIDTH, kAppWidth_Mini(200));
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        GoodsDetailSpecTitleView *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"GoodsDetailSpecTitleView" forIndexPath:indexPath];
        return headView;
    }else{
        GoodsDetailBuyCountView *footerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"GoodsDetailBuyCountView" forIndexPath:indexPath];
        __weak typeof(self) weakSelf = self;
        footerView.nowCount = ^(NSInteger count) {
            if (weakSelf.buyInfoModel.skuModel) {
                NSInteger stockNum = weakSelf.buyInfoModel.skuModel.stockNum;
                if (stockNum < count) {
                    weakSelf.countView.buyCount = stockNum;
                    weakSelf.buyInfoModel.count = stockNum;
                }else{
                    weakSelf.buyInfoModel.count = count;
                }
            }else{
                weakSelf.countView.buyCount = 1;
            }
        };
        self.countView = footerView;
        if (self.buyInfoModel.skuModel) {
            NSInteger stockNum = weakSelf.buyInfoModel.skuModel.stockNum;
            footerView.maxCount = stockNum;
            if (self.buyInfoModel.count > stockNum) {
                self.buyInfoModel.count = stockNum;
            }
            footerView.buyCount = self.buyInfoModel.count;
        }else{
            footerView.maxCount = 0;
            footerView.buyCount = 1;
        }
        return footerView;
    }
}

#pragma mark - UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (!self.buyInfoModel.colorModel) {
        NSLog(@"先选颜色");
        return;
    }
    SaleAttr2ListModel *model = self.detailModel.saleAttrList.saleAttr2List[indexPath.row];
    if (!model.isStock) {
        return;
    }
    self.buyInfoModel.sizeModel = model;
    
    
//    GoodDetailsSkusObject *model = self.dataArray[indexPath.row];
//    if (model.skuStock == 0) {
//        return;
//    }
//    if (self.selectObject) {
//        if (self.selectObject.buyCount < model.skuStock) {
//            model.buyCount = self.selectObject.buyCount;
//        }else{
//            model.buyCount = model.skuStock;
//        }
//    }
//    if (model.isSelect) {
//        self.selectObject = nil;
//        model.isSelect = NO;
//        self.headView.dataObject = self.detailModel;
//    }else{
//        self.selectObject.isSelect = NO;
//        model.isSelect = YES;
//        self.selectObject = model;
//        self.headView.dataObject = self.selectObject;
//    }
    [self.myCollectionView reloadData];
}

#pragma mark - 懒加载
-(SelectHeadView *)headView{
    if (!_headView) {
        _headView  = [[SelectHeadView alloc]init];
    }
    return _headView;
}

#pragma mark - 监听到键盘弹出
- (void)keyboardWillShow:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    CGFloat keyboardheight = keyboardF.size.height;
    
    //获取当前第一响应状态的输入框
    UIWindow * keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *view = [keyWindow performSelector:@selector(firstResponder)];
    //输入框在当前屏幕的坐标y
    CGFloat maxY =  CGRectGetMaxY([view convertRect:view.bounds toView:[[[UIApplication sharedApplication] delegate] window]]);
    //判断是非遮挡当前输入框，小于0遮挡，大于或等于0没有
    CGFloat map = SCREEN_HEIGHT - maxY - keyboardheight;
    if (map < 0){
        [UIView animateWithDuration:duration animations:^{
            self.view.transform = CGAffineTransformMakeTranslation(0, map);
//            self.view.transform = CGAffineTransformMakeTranslation(0, map);
        }];
    }
}

#pragma mark - 监听到键盘收起
- (void)keyboardWillHide:(NSNotification *)notification{
    NSDictionary *userInfo = notification.userInfo;
    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] floatValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.transform = CGAffineTransformIdentity;
    }];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

@end
